﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using NetFrameworkExtensions.Reflection;

namespace NetFrameworkExtensions.Enterprise.Composition
{
  // TODO: Create a bootstrapper base class in NetFrameworkExtensions.Enterprise
  public class MEFBootstrapper
  {
    public CompositionContainer Container { get; private set; }

    public void Run()
    {
      var catalog = new AggregateCatalog();
      ConfigureCatalogs(catalog);

      Container = CreateContainer(catalog);

      ServiceManager.SetServiceManagerProvider(() => new MEFServiceManagerAdapter(Container));
    }

    protected virtual void ConfigureCatalogs(AggregateCatalog catalog)
    {
      var localFolder = Assembly.GetEntryAssembly().GetLocalPath();
      catalog.Catalogs.Add(new DirectoryCatalog(localFolder, "*.dll"));
      catalog.Catalogs.Add(new DirectoryCatalog(localFolder, "*.exe"));
    }

    protected virtual CompositionContainer CreateContainer(AggregateCatalog catalog)
    {
      return new CompositionContainer(catalog);
    }
  }
}
